# This is a little convoluted, but it's the only way I can get this to work...
# the merge is performed with one key column, the others are merged in
# at the end.

# The key column to merge by
merge_key 			<- "SystematicName"

# These are the non-unique columns
merge_const_str	<- c("GeneName", "Description", "Probe_Name", "Chrom_Loc")
merge_const			<- c()

set_merge_const 	<- function(dat) {
	for(i_str in merge_const_str) {
		merge_const = c(merge_const, grep(i_str, colnames(dat)))
	}
	merge_const
}


loadf					<- function(name) {
	print(paste(c("Loading...", name), collapse = " "))
	(read.csv(name, sep = "\t", head = TRUE))#[,c(1,4,7:16)]
}


merge_em 	<- function(car_dat, cdr_dats, counter = 1) {

	# Load up the first file in cdr_dats
	car_cdr = loadf(cdr_dats[1])

	if(is.null(car_dat) && !is.null(cdr_dats)) {
		merge_em(car_cdr, cdr_dats[2:length(cdr_dats)], 1)
	} else {
		# Merge two files
		print(paste(c("Merging in", cdr_dats[1]), collapse = " "))
		merge_const <- set_merge_const(car_cdr)
		print(merge_key)
		temp_merge 	<- merge(car_dat, car_cdr[,-merge_const], by = merge_key, suffix = c("", paste(c("_", counter), collapse = "")))

		if(length(cdr_dats) > 1)
			merge_em(temp_merge, cdr_dats[2:length(cdr_dats)], counter + 1)
		else
			temp_merge;
	}
		
}

get_args		<- function(arg_name, args) {
	arg_name.full = paste(c("--", arg_name, "="), collapse = "")
	strsplit(sub(arg_name.full, "", args[grep(arg_name.full, args)]), ",")
}

args 		<- commandArgs()
files 	<- (get_args("in_files", args))[[1]]
out_file <- (get_args("out_file", args))[[1]]

merged = merge_em(NULL, files)

print(paste(c("Writing to", out_file), collapse = " "))
write.table(merged, file = out_file, sep = "\t", row.names = FALSE, quote = FALSE)
